#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: lijk34925
@Time: 2023/5/10 21:30
@File: fields_map.py
"""
from typing import Union, List

from jinja2 import Environment
from datetime import datetime, timedelta

"""
使用jinjia2模板，添加自定义的filter函数使用
"""


class FieldsMap:
    def __init__(self):
        self.env = Environment()
        self.add_filter_fnc()
        self.aml_ini_date = ""

    def add_filter_fnc(self):
        self.env.filters['split'] = self.__split
        self.env.filters['cal_before_date'] = self.__cal_before_date

    @staticmethod
    def __is_number(value):
        try:
            float(value)
            return True
        except Exception:
            return False

    def parse_template(self, origin_value: str, kwargs: dict) -> str:
        """
        解析模板内容，填充变量的实际值
        :param origin_value:
        :param kwargs:
        :return:
        """
        parser_result = self.env.from_string(origin_value)
        result = parser_result.render(**kwargs)
        return result

    def get_parse_result(self, origin_value: str, kwargs: dict) -> object:
        """
        解析模板，并判断返回值的类型
        :param origin_value:
        :param kwargs:
        :return:
        """
        result = self.parse_template(origin_value, kwargs).strip()
        # 判断值的真是类型并返回
        if result.startswith('[') and result.endswith(']'):
            result_new = eval(result)
        elif result.startswith('{') and result.endswith('}'):
            result_new = eval(result)
        elif self.__is_number(result) and '.' in result:
            result_new = float(result)
        elif self.__is_number(result) and '.' not in result:
            result_new = int(result)
        else:
            result_new = result
        return result_new

    @staticmethod
    def __split(origin_value: str, split_flag: str = ',') -> Union[List[str], str]:
        if isinstance(origin_value, str):
            return origin_value.split(split_flag)
        else:
            return origin_value

    def __cal_before_date(self, days, out_format="%Y%m%d", date_flag: str = 'aml') -> str:
        # 获取当前日期
        if self.aml_ini_date and date_flag == 'aml':
            now = datetime.strptime(self.aml_ini_date, "%Y%m%d")
        else:
            now = datetime.now()
        # 计算前1000天的日期
        past = now - timedelta(days=int(days))
        return past.strftime(out_format)
